package main;

import com.item.manager.FlagAttribute;
import com.item.manager.Template;
import encounter.Encounter;

public class Trap implements Encounter {
    private final String name;
    private final int spotDifficulty;
    private final int disarmDifficulty;
    private final int evadeDifficulty;
    private final int damage;
    private final boolean oneOff;

    public Trap(Template template) {
        this.name = template.name();
        this.spotDifficulty = template.findAttr("spotDifficulty").asInt();
        this.disarmDifficulty = template.findAttr("disarmDifficulty").asInt();
        this.evadeDifficulty = template.findAttr("evadeDifficulty").asInt();
        this.damage = template.findAttr("damage").asInt();
        this.oneOff = ((FlagAttribute) template.findAttr("oneOff")).value();
    }

    @Override
    public String toString() {
        return this.name;
    }

    @Override
    public boolean resolve(Hero hero) {
        Logger.log("-----------------------------");
        boolean disarmed = false;

        int spotRoll = RandomProvider.roll(hero.getSpot());
        int concealRoll = RandomProvider.roll(spotDifficulty);
        if (spotRoll > concealRoll) {
            Logger.log(hero + " spots " + this + ".");
        } else {
            disarmed = oneOff;
            hit(hero);
        }

        if (!disarmed && hero.getTraps() >= disarmDifficulty) {
            int disarmRoll = RandomProvider.roll(hero.getTraps());
            int trapRoll = RandomProvider.roll(disarmDifficulty);

            if (disarmRoll > trapRoll) {
                disarmed = true;
                Logger.log(hero + " disarms " + this + ".");
                hero.addEvent("Disarms " + this + ".");
            } else {
                disarmed = oneOff;
                hit(hero);
            }
        }

        hero.updateEnergy(-0.01);
        Logger.log("-----------------------------");
        return false;
    }

    private void hit(Hero hero) {
        int damageDealt = 0;
        for (int i = 0; i < damage; i++) {
            int evadeRoll = RandomProvider.roll(hero.getEvade());
            int trapRoll = RandomProvider.roll(evadeDifficulty);
            if (evadeRoll <= trapRoll) {
                damageDealt++;
            }
        }

        if (damageDealt == 0) {
            Logger.log(hero + " evades " + this + ".");
            hero.addEvent("Evades " + this + ".");
        } else {
            Logger.log(this + " hits " + hero + " for " + damageDealt + " damage.");
            hero.addEvent("Is hit by " + this + " for " + damageDealt + ".");
            hero.updateHealth(-damageDealt);
        }
    }
}
